import { inject, reactive, ref, watch, unref, Ref, computed } from 'vue';
import { useMessage } from '@/hooks/web/useMessage';
import { request } from '@pkg/request/src';
import { componentSetting } from '@pkg/setting';
const { searchForm } = componentSetting;
export function useSelectModal(props) {
  //接收下拉框选项
  const selectOptions: any = inject('selectOptions', ref([]));
  //接收已选择的值
  const selectValues = <object>inject('selectValues', reactive({ value: [], change: false }));
  //已选择的值
  const checkedKeys = ref<Array<string | number>>([]);
  //选则的行记录
  const selectRows = ref<Array<object>>([]);
  //查询表单
  const formConfig = props.formConfig;
  //提示弹窗
  const { createMessage } = useMessage();

  /**
   * 监听selectValues变化
   */
  watch(
    selectValues,
    () => {
      //设置列表默认选中
      checkedKeys['value'] = selectValues['value'];
    },
    { immediate: true },
  );

  async function onSelectChange(selectedRowKeys: (string | number)[], selectRow) {
    checkedKeys.value = selectedRowKeys;
    //判断全选的问题checkedKeys和selectRows必须一致
    if (props.showSelected && unref(checkedKeys).length !== unref(selectRow).length) {
      const { records } = await getList({
        code: unref(checkedKeys).join(','),
        pageSize: unref(checkedKeys).length,
      });
      selectRows.value = records;
    } else {
      selectRows.value = selectRow;
    }
  }

  /**
   * 选择列配置
   */
  const rowSelection: any = {
    //动态设置rowSelection的type值,默认checkbox
    type: props.isRadioSelection ? 'radio' : 'checkbox',
    columnWidth: 20,
    selectedRowKeys: checkedKeys,
    onChange: onSelectChange,
  };

  /**
   * 序号列配置
   */
  const indexColumnProps = {
    dataIndex: 'index',
    width: 50,
  };

  /**
   * 查询表单配置
   */
  const getFormConfig = computed(() => {
    return {
      ...searchForm,
      ...formConfig,
    };
  });

  async function initSelectRows() {
    const { records } = await getList({
      code: selectValues['value'].join(','),
      pageSize: selectValues['value'].length,
    });
    checkedKeys['value'] = selectValues['value'];
    selectRows['value'] = records;
  }

  /**
   * 弹出框显示隐藏触发事件
   */
  async function visibleChange(visible) {
    console.info('visibleChange:', 1);
    if (visible) {
      //设置列表默认选中
      props.showSelected && (await initSelectRows());
    }
  }

  /**
   * 请求列表数据
   * @param params
   */
  async function getList(params) {
    console.info('getList:', params);
    return request.get({ url: '/role/page', params }, { successMessageMode: 'none' });
  }

  /**
   * 确定选择
   */
  function getSelectResult(success) {
    const options = <any[]>[];
    const values = <any[]>[];
    selectRows.value.forEach((item) => {
      options.push({ label: item[props.labelKey], value: item[props.rowKey] });
    });
    checkedKeys.value.forEach((item) => {
      values.push(item);
    });
    selectOptions.value = options;
    if (props.maxSelectCount && values.length > props.maxSelectCount) {
      createMessage.warning(`最多只能选择${props.maxSelectCount}条数据`);
      return false;
    }
    success && success(options, values,selectRows.value);
  }
  //删除已选择的信息
  function handleDeleteSelected(record) {
    checkedKeys.value = checkedKeys.value.splice(checkedKeys.value.indexOf(record['id']), 1);
    selectRows.value = selectRows.value.filter((item) => item['id'] !== record['id']);
  }
  //清空选择项
  function reset() {
    checkedKeys.value = [];
    selectRows.value = [];
  }
  return [{ onSelectChange, visibleChange, selectOptions, selectValues, rowSelection, indexColumnProps, checkedKeys, selectRows, getSelectResult, handleDeleteSelected, reset, getFormConfig, getList }];
}
